/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */

#include "NativeFile.h"

namespace PQCore
{
	NativeFile::NativeFile(std::string fileName)
		: FileBase(fileName),_buf(0),_eof(true),_len(0),_pos(0)
	{
		FILE* file=fopen(fileName.c_str(),"rb");//wb+ write file
		if(!file){
			_ok=false;
			return;
		}
		fseek(file,0L,SEEK_END);

		_len=ftell(file);
		_eof=false;
		_buf=new char[_len];
		fseek(file,0L,SEEK_SET);
		fread(_buf,1,_len,file);

		fclose(file);
		_ok=true;
	}

	NativeFile::~NativeFile()
	{
		if(_buf){
			delete _buf;
		}
	}

	bool NativeFile::isExist(std::string fileName)
	{
		FILE *file=fopen(fileName.c_str(),"rb");
		if (file == NULL){
			return false;
		}
		fclose(file);
		return true;
	}

	size_t NativeFile::read(void* dest, size_t bytes)
	{
		if(_buf){
			if(_pos>=_len){
				_eof=true;
				_pos=0;
				return 0;
			}
			if(_pos+bytes>_len){
				int len=_len-_pos;
				memcpy(dest,(char*)_buf+_pos,len);
				_pos+=len;
				return len;
			}
			memcpy(dest,(char*)_buf+_pos,bytes);
			_pos+=bytes;
			return bytes;
		}
		return 0;
	}

	bool NativeFile::eof()
	{
		return _eof;
	}

	int NativeFile::getSize()
	{
		return _len;
	}

	SerializeDatagram* NativeFile::readDatagram(std::string fileName)
	{
		FILE* file=fopen(fileName.c_str(),"rb");//
		if(!file){
			return 0;
		}

		fseek(file,0L,SEEK_END);
		int length=ftell(file);
		char* buf=new char[length];
		fseek(file,0L,SEEK_SET);
		fread(buf,1,length,file);
		fclose(file);
		SerializeDatagram* datagram=new SerializeDatagram(buf,length);
		delete[] buf;

		return datagram;
	}


	void NativeFile::write(std::string fileName,SerializeDatagram* dgram)
	{
		FILE* file=fopen(fileName.c_str(),"wb");
		fseek(file,0L,SEEK_SET);
		fwrite(dgram->data(),1,dgram->length(),file);
		fclose(file);
		
	}


}
